<template>
    <div class="mainDiv">
        <el-row :gutter="20" style="height: 100%;color:#000;margin: 0px; padding: 10px">
            <el-col :span="12" class="flex_center" style="height: 100%">      
                <el-card :body-style="{ padding: '0px',height: '100%',display: 'flex','flex-direction': 'column' }" style="width: 375px;margin: 0 auto;height: 100%;">
                <el-upload class="avatar-uploader" action="" :show-file-list="false" :auto-upload="false" :on-change="changeImg">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon">添加标题图片</i>
                </el-upload>

                <el-input style="font-weight: 900" v-model="title" placeholder="文章标题（最多不能超过30个字）"></el-input>

          <quill-editor v-model="content" ref="myQuillEditor" :options="editorOption" style="height:100%;display: flex;flex-direction: column;">
          </quill-editor>
            <div style="padding: 14px;">
              <span>主题内容</span>
              <div class="bottom clearfix">
                <time style="font-size: 12px">呈现在首页部分</time>
                <el-button type="primary" size="mini" style="float:right" @click="save">保存</el-button>
              </div>
            </div>
          </el-card>
            </el-col>
            <el-col :span="12" class="flex_center" style="height: 100%">
                
                <div id="iphone">
                <div class="ql-container ql-snow" style="display:flex;flex-direction:column;">
                    <img v-if="imageUrl" :src="imageUrl" style="width: 100%; height: 200px">
                    <h2 style="text-align: center;padding: 10px 0 0 0;">{{title}}</h2>
                    <div class="ql-editor" v-html="content"></div>
                </div>
                </div>
            </el-col>
        </el-row>
    </div>
</template>
<script>
import {
  quillEditor
} from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import * as qiniu from 'qiniu-js'
import AdminEdit from '@/service/organization/adminEdit.js'
import C from '@/common/common.js'
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike', 'blockquote', {
    'list': 'ordered'
  }, {
    'list': 'bullet'
  }, {
    'indent': '-1'
  }, {
    'indent': '+1'
  }, {
    'align': []
  }, {
    'color': []
  }, {
    'background': []
  }, {
    'size': ['small', false, 'large', 'huge']
  }, {
    'header': [1, 2, 3, 4, 5, 6, false]
  }, 'image', 'clean'] // toggled buttons
]
export default {
  data () {
    let that = this
    return {
      editorOption: {
        modules: {
          toolbar: {
            container: toolbarOptions, // 工具栏
            handlers: {
              'image': function (value) {
                if (value) {
                  // 打开图片窗口
                  const {
                    dialog
                  } = require('electron').remote
                  dialog.showOpenDialog({
                    filters: [{
                      name: 'Images',
                      extensions: ['jpg', 'jpeg', 'png', 'gif']
                    }]
                  }, async (files) => {
                    if (files) {
                      console.log(files)
                      const fs = require('fs')
                      let file = fs.readFileSync(files[0])
                      console.log(file)
                      file = new Blob([file])
                      console.log(file)
                      if (file.size / (1024 * 1024) > 2) {
                        that.$message.error('上传图片大于2M')
                        return false
                      }
                      let token = await AdminEdit.getToken({})
                      let name = files[0].split('\\').pop()
                      let keyName =
                          new Date().getFullYear() +
                          '/' +
                          (new Date().getMonth() + 1) +
                          '/' +
                          new Date().getDate() +
                          '/' +
                          name
                      let observable = qiniu.upload(file, keyName, token.uptoken)
                      observable.subscribe({
                        next (res) {
                          console.log(res)
                        },
                        error (err) {
                          if (err) {
                            console.log(err)
                          }
                          that.$message.error('上传失败！')
                        },
                        complete (res) {
                          console.log(res)
                          // 上传成功后开始提交表格
                          let asd = `http://pde4eshzp.bkt.clouddn.com/${res.key}`
                          // that.submitForm()
                          let quill = that.$refs.myQuillEditor.quill
                          let length = quill.getSelection().index
                          quill.insertEmbed(length, 'image', asd)
                          quill.setSelection(length + 1)
                        }
                      })
                    }
                  })
                } else {
                  this.quill.format('image', false)
                }
              }
            }
          }
        }
      },
      imageUrl: '',
      imagefile: '',
      title: '',
      content: '',
      id: ''
    }
  },
  methods: {
    async changeImg (file, fileList) {
      const isJPG =
          file.raw.type === 'image/jpeg' ||
          file.raw.type === 'image/png' ||
          file.raw.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片格式错误!')
        return
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return
      }
      this.imagefile = file
      this.imageUrl = file.url
    },
    async save () {
      let that = this
      if (this.imagefile.name) {
        // 开始获取上传的token
        let token = await AdminEdit.getToken({})
        let keyName =
            new Date().getFullYear() +
            '/' +
            (new Date().getMonth() + 1) +
            '/' +
            new Date().getDate() +
            '/' +
            this.imagefile.name
        let observable = qiniu.upload(this.imagefile.raw, keyName, token.uptoken)
        observable.subscribe({
          next (res) {
            console.log(res)
          },
          error (err) {
            if (err) {
              console.log(err)
            }
            this.loading = false
            that.$message.error('上传失败！')
          },
          async complete (res) {
            // 上传成功后开始提交表格
            that.imageUrl = `http://pde4eshzp.bkt.clouddn.com/${res.key}`
            let data = {
              articleimg: that.imageUrl,
              title: that.title,
              body: that.content,
              id: that.id
            }
            let resdata = await C.ajax('/shop/miniProgram/saveArticle', data, 'post')
            if (resdata) {
              that.$message.success(resdata.data)
            } else {
              that.$message.error(resdata.data)
            }
          }
        })
      } else {
        let data = {
          title: that.title,
          body: that.content,
          id: that.id
        }
        let resdata = await C.ajax('/shop/miniProgram/saveArticle', data, 'post')
        if (resdata) {
          that.$message.success(resdata.data)
        } else {
          that.$message.error(resdata.data)
        }
      }
    }
  },
  mounted: async function () {
    let id = C.getDatas().id
    if (id) {
      let article = await C.ajax('/shop/miniProgram/getArticleInfo', {id: id})
      if (article) {
        this.imageUrl = article.articleimg
        this.title = article.title
        this.content = article.body
        this.id = article.id
      }
    }
  },
  components: {
    quillEditor
  }
}
</script>

<style>
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 300px;
    height: 200px;
    line-height: 200px;
    text-align: center;
  }
.avatar {
    width: 100%;
    height: 200px;
    display: block;
  }
  .ql-toolbar.ql-snow .ql-formats {
        margin-right: 0px;
 }
 .el-input__inner {
     border-radius: 0px
 }
 .ql-toolbar.ql-snow + .ql-container.ql-snow {
    overflow-y: auto;
}
.avatar-uploader-icon{
    width: 375px
}

#iphone {
    width: 352px;
    height: 100%;
    position: relative;
    display: inline-block;
    border: 1px solid #000;
    border-radius: 40px;
    padding: 70px 10px;
    flex-shrink: 0;
    margin: 0 auto;
    box-sizing: border-box;
  }
  #iphone:before {
    position: absolute;
    top: 30px;
    left: 50%;
    content: "";
    display: inline-block;
    width: 80px;
    height: 8px;
    margin-left: -40px;
    border: 1px solid #000;
    border-radius: 8px;
  }
  #iphone:after {
    position: absolute;
    left: 50%;
    bottom: 15px;
    content: "";
    display: block;
    width: 40px;
    height: 40px;
    margin-left: -20px;
    border: 1px solid #000;
    border-radius: 50%;
  }
</style>